package com.fingard.dsp.bank.directbank.bea01;

import java.util.Calendar;
import java.util.Date;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.bankInterface.ITransaction;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7515TodayTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7516HisTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.RetAtsTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.detail.RetAtsTransDetail;
import com.fingard.text.StringHelper;
import com.fingard.util.DateHelper;
import com.fingard.xml.XElement;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

public class BEA01Transaction extends BEA01Base implements ITransaction {
    @Override
    public RetAtsTrans d_7516_HisTrans(Req7516HisTrans p_req7516) throws Exception {
        //历史明细查询返回ATS的对象
        RetAtsTrans retAts = new RetAtsTrans(p_req7516.reqHeader);
        String tmpRespCode = "";
        String tmpRespInfo = "";
        retAts.writeStart();//写返回ATS的统一头部信息
        try {
            Calendar tmpCalendarFrom = Calendar.getInstance();
            tmpCalendarFrom.setTime(p_req7516.getDateFrom());
            Calendar tmpCalendarTo = Calendar.getInstance();
            tmpCalendarTo.setTime(p_req7516.getDateTo());

            int tmpIntDateFrom = 0;
            int tmpIntDateTo = 0;
            //按自然月循环查询
            while (tmpIntDateFrom <= tmpIntDateTo && tmpRespCode.length() == 0) {
                Calendar tmpClndrStepTo = Calendar.getInstance();
                tmpClndrStepTo.setTime(tmpCalendarFrom.getTime());
                //判断是否跨月
                if (DateHelper.compareMonth(tmpCalendarFrom, tmpCalendarTo) == -1) {
                    //跨月则设置为月末
                    tmpClndrStepTo.set(Calendar.DAY_OF_MONTH, tmpClndrStepTo.getActualMaximum(Calendar.DAY_OF_MONTH));
                } else {
                    tmpClndrStepTo.setTime(tmpCalendarTo.getTime());
                }

                boolean isContinue = true;
                int currPageNum = 0;
                int eachPageNum = 50;

                while (tmpRespCode.length() == 0) {//分页查询
                    BEA01Header bankHeader = new BEA01Header();
                    bankHeader.TRAN_REF_NO = getQryTransID();//报文编号 字母数字串 0-12位
                    bankHeader.SERVICE_CODE = "2301";//交易代码
                    XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
                    //写入通用的头部节点，<trans>之后
                    writeCommonHeader(xmlWriter, bankHeader);
                    xmlWriter.writeElementString("TOTAL_NUM", eachPageNum + "");
                    xmlWriter.writeElementString("CURRENT_NUM", currPageNum + "");
                    xmlWriter.writeElementString("ACCT_NO", p_req7516.actNum);
                    xmlWriter.writeElementString("CCY", convertCurToBank(p_req7516.actCur));
                    xmlWriter.writeElementString("START_DATE", Format.Date8Format.format(tmpCalendarFrom.getTime()));
                    xmlWriter.writeElementString("END_DATE", Format.Date8Format.format(tmpClndrStepTo.getTime()));
                    xmlWriter.writeElementString("reqTime", "", true);
                    xmlWriter.writeElementString("CHECKPS", "", true);
                    xmlWriter.writeEndDocument();

                    String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());
                    XmlTextReader tmpBkReader;
                    int tmpPageRdNum;
                    int tmpCurrRdNum;
                    if (tmpStrRet[0].length() == 0) {
                        StringBuilder tmpSbMsg = new StringBuilder();
                        tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                        if (tmpBkReader != null) {
                            String retCode = tmpBkReader.getFirstText("/BCDL/opRep/retCode");
                            String errMsg = tmpBkReader.getFirstText("/BCDL/opRep/errMsg");
                            if ("000000".equals(retCode) || "查询无返回记录".equals(errMsg)) {
                                //String
                                tmpPageRdNum = StringHelper.convertStrToIntIgnoreEmptyOrNull(tmpBkReader.getFirstText("/BCDL/opRep/opResult/TOTAL_NUM"));
                                tmpCurrRdNum = StringHelper.convertStrToIntIgnoreEmptyOrNull(tmpBkReader.getFirstText("/BCDL/opRep/opResult/CURRENT_NUM"));
                                if (tmpPageRdNum > 0) {
                                    while (tmpBkReader.read("/BCDL/opRep/opResultSet/opResult")) {
                                        RetAtsTransDetail tmpRetDetail = new RetAtsTransDetail();
                                        XElement tmpRetNode = tmpBkReader.readedXElement;

                                        String cdflag = tmpRetNode.getSingleText("CR_DR_MAINT_IND");//D 借 C贷
                                        String amout = tmpRetNode.getSingleText("TRAN_AMT");
                                        if ("D".equals(cdflag)) {
                                            if (amout.contains("-")) {
                                                tmpRetDetail.cdFlag = "2";
                                            } else {
                                                tmpRetDetail.cdFlag = "1";
                                            }
                                        } else if ("C".equals(cdflag)) {
                                            if (amout.contains("-")) {
                                                tmpRetDetail.cdFlag = "1";
                                            } else {
                                                tmpRetDetail.cdFlag = "2";
                                            }
                                        } else {
                                            tmpRespCode = "-1";
                                            tmpRespInfo = "借贷标志( " + cdflag + ")无法识别，请与银行核对";
                                            break;
                                        }
                                        tmpRetDetail.tranAmt = StringHelper.amtDiv100RetZeroIfNullOrEmpty(amout.replace("-", "").replaceFirst("^0*", ""));
                                        tmpRetDetail.accBal = StringHelper.amtDiv100RetZeroIfNullOrEmpty(tmpRetNode.getSingleTextNotNull("ACTUAL_BAL_AMT").replace("-", "").replaceFirst("^0*", ""));
                                        tmpRetDetail.tranDate = Format.strToDateFormat("yyyyMMdd", "yyyy-MM-dd", tmpRetNode.getSingleTextNotNull("TRAN_DATE_1"));
                                        tmpRetDetail.valueDate = tmpRetDetail.tranDate;
                                        String tmpTime = tmpRetNode.getSingleTextNotNull("MAK2");
                                        if (tmpTime.length() == 6) {
                                            tmpTime = Format.strToDateFormat("HHmmss", "HH:mm:ss", tmpTime);
                                        } else {
                                            tmpTime = "00:00:00";
                                        }
                                        tmpRetDetail.tranTime = tmpRetDetail.tranDate + " " + tmpTime;
                                        tmpRetDetail.recAccNum = tmpRetNode.getSingleTextNotNull("TFR_ACCT_NO");
                                        tmpRetDetail.busType = tmpRetNode.getSingleTextNotNull("TRAN_TYPE");
                                        tmpRetDetail.cur = convertCurToATS(tmpRetNode.getSingleTextNotNull("CCY"));
                                        tmpRetDetail.payCode = tmpRetNode.getSingleTextNotNull("REFERENCE");
                                        tmpRetDetail.usage = tmpRetNode.getSingleTextNotNull("TRAN_DESC");
                                        tmpRetDetail.abstr = pickupAbstr(tmpRetDetail.usage, tmpRetDetail.payCode);
                                        tmpRetDetail.recAccNum = tmpRetNode.getSingleTextNotNull("TFR_ACCT_NO");
                                        tmpRetDetail.recAccName = tmpRetNode.getSingleTextNotNull("TFR_ACCT_NAME");
                                        tmpRetDetail.recAccBank = tmpRetNode.getSingleTextNotNull("REFERENCE_BRANCH");
                                        retAts.writeRetDetail(tmpRetDetail);
                                    }
                                }
                            } else {
                                tmpRespCode = "-1";
                                tmpRespInfo = errMsg;
                                break;
                            }
                        } else {
                            tmpRespCode = "-1";
                            tmpRespInfo = tmpSbMsg.toString();
                            break;
                        }
                    } else {
                        tmpRespCode = "-1";
                        tmpRespInfo = tmpStrRet[1];
                        break;
                    }
                    if (tmpPageRdNum != eachPageNum) {
                        break;
                    }
                    currPageNum = tmpCurrRdNum + tmpPageRdNum;
                }
                tmpCalendarFrom = tmpClndrStepTo;
                tmpCalendarFrom.add(Calendar.DAY_OF_MONTH, 1);
                tmpIntDateFrom = Integer.parseInt(Format.Date8Format.format(tmpCalendarFrom.getTime()));
                tmpIntDateTo = Integer.parseInt(Format.Date8Format.format(tmpCalendarTo.getTime()));
            }
        } catch (Exception e) {
            tmpRespCode = "-1";
            tmpRespInfo = e.getMessage();
            e.printStackTrace();
        }
        if ("-1".equals(tmpRespCode)) {
            retAts = new RetAtsTrans(p_req7516.reqHeader);
            retAts.writeStart();//写返回ATS的统一头部信息
            retAts.writeRespCode(tmpRespCode);
            retAts.writeRespInfo(tmpRespInfo);
        } else if (retAts.getWrittenRdCount() == 0) {
            retAts.writeRespCode("0");
            retAts.writeRespInfo("交易为空");
        }
        retAts.writeEnd();
        return retAts;
    }

    @Override
    public RetAtsTrans d_7515_TodayTrans(Req7515TodayTrans p_req7515) throws Exception {
        Req7516HisTrans tmpReq7516 = new Req7516HisTrans(p_req7515.reqHeader);
        tmpReq7516.actArea = p_req7515.actArea;
        tmpReq7516.actCur = p_req7515.actCur;
        tmpReq7516.actNum = p_req7515.actNum;
        String tmpStrToday = Format.Date8Format.format(new Date());
        tmpReq7516.dateFrom = tmpStrToday;
        tmpReq7516.dateTo = tmpStrToday;
        return d_7516_HisTrans(tmpReq7516);
    }
}
